<?php

namespace app\admin\controller\admin;

use app\admin\controller\Controller;
use app\admin\model\admin\User as AdminUserModel;
use think\Db;

/**
 * 区域管理
 */
class User extends Controller{
    protected $model;
    public function _initialize(){
        parent::_initialize();
        $this->model=new AdminUserModel();
    }
    /**
     * 获取区域列表
     */
    public function index(){
        // 获取全部数据列表
        $type=input('get.type');
        $title=input('get.name');
        if($title){
            $where['name']=["like",'%'.trim($title).'%'];
        }
        if($type){
            $where['type']=["=",$type];
        }
        if($type||$title){
            $list=Db::name('love_area')->where($where)->order('create_time desc')->paginate(15, false, [
                'query' => \request()->request()
            ]);
        }else{
            $list=Db::name('love_area')->order('create_time desc')->paginate(15, false, [
                'query' => \request()->request()
            ]);
        }
        return $this->fetch('index', compact('list'));
    }
    /**
     * 添加区域
     */
    public function add(){
        if(!$this->request->isAjax()){
            //获取顶级数据列表
            $roleList=Db::name('love_area')->where(['pid'=>0,'status'=>1])->select();
            return $this->fetch('add', compact('roleList'));
        }
        // 新增记录
        $data=$this->postData('user');
        if($data['type']==1){
            $data['pid']=0;
            $data['datatype']=0;
        }
        $data['create_time']=time();
        $data['update_time']=0;
        $add=Db::name('love_area')->insertGetId($data);
        if($add){
            return $this->renderSuccess('添加成功',url('admin.user/index'));
        }
        return $this->renderError( $this->model->getError()?:'添加失败');
    }
    /**
     * 编辑区域
     */
    public function edit($user_id){
        //区域详情
        if (!$this->request->isAjax()) {
            $model=Db::name('love_area')->where(['id'=>$user_id])->find();
            return $this->fetch('edit',[
                'model'=>$model,
            ]);
        }
        $add=Db::name('love_area')->where(['id'=>$user_id])->update(['name'=>$this->postData('user')['name']]);
        //更新记录
        if ($add){
            return $this->renderSuccess('更新成功',url('admin.user/index'));
        }
        return $this->renderError($this->model->getError()?:'更新失败');
    }
    /**
     * 禁用
     */
    public function delete($user_id){
        $status=input('get.status');
        $update=Db::name('love_area')->where(['id'=>$user_id])->update(['status'=>$status]);
        if($update){
            return $this->renderSuccess('禁用成功', url('admin.user/index'));
        }
        return $this->renderError($this->model->getError()?:'禁用失败');
    }
}
